package com.yupi.loveplanneraiagent.advisor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import reactor.core.publisher.Flux;

import java.util.Set;
import java.util.regex.Pattern;

/**
 * 违禁词校验Advisor
 * 用于在用户输入中检测违禁词（如黄赌毒等）
 */
@Slf4j
public class ProhibitedWordsAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

    // 定义违禁词集合
    private static final Set<String> PROHIBITED_WORDS = Set.of(
            "色情", "黄色", "黄片", "黄色网站", "情色", "低俗",
            "赌博", "赌球", "赌马", "赌钱", "赌桌", "赌场", "赌资",
            "毒品", "吸毒", "贩毒", "海洛因", "冰毒", "摇头丸", "大麻", "K粉",
            "暴力", "恐怖", "枪支", "炸弹", "自杀", "自残", "极端主义", "恐怖主义",
            "政治敏感", "反政府", "颠覆国家", "分裂国家", "泄露国家机密"
    );

    // 创建违禁词的正则表达式模式（用于更灵活的匹配）
    private static final Pattern PROHIBITED_PATTERN = createProhibitedPattern();

    private static Pattern createProhibitedPattern() {
        String regex = String.join("|", PROHIBITED_WORDS.stream()
                .map(Pattern::quote)
                .toArray(String[]::new));
        return Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        // 设置优先级，通常在其他处理之前执行
        return Integer.MIN_VALUE; // 最高优先级
    }

    /**
     * 在请求处理前检查违禁词
     */
    private AdvisedRequest before(AdvisedRequest request) {
        String userText = request.userText();
        if (userText != null && containsProhibitedWords(userText)) {
            log.warn("检测到违禁内容，请求被拦截: {}", userText);
            throw new IllegalArgumentException("您的输入包含违禁内容，无法处理。");
        }
        return request;
    }

    /**
     * 检查文本是否包含违禁词
     * @param text 待检查的文本
     * @return 如果包含违禁词返回true，否则返回false
     */
    private boolean containsProhibitedWords(String text) {
        if (text == null || text.trim().isEmpty()) {
            return false;
        }

        // 方法1: 使用正则表达式进行匹配
        if (PROHIBITED_PATTERN.matcher(text).find()) {
            return true;
        }

        // 方法2: 使用精确词汇匹配（作为补充）
        for (String prohibitedWord : PROHIBITED_WORDS) {
            if (text.toLowerCase().contains(prohibitedWord.toLowerCase())) {
                return true;
            }
        }

        return false;
    }

    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        advisedRequest = this.before(advisedRequest);
        return chain.nextAroundCall(advisedRequest);
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        advisedRequest = this.before(advisedRequest);
        return chain.nextAroundStream(advisedRequest);
    }
}



